package cn.copera.dyy.web;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.copera.dyy.common.test.ImageUtil;
import cn.copera.dyy.common.utils.FileUtils;
import cn.copera.dyy.common.utils.StringUtils;
import cn.copera.dyy.common.web.BaseController;
import cn.copera.dyy.entity.ExchangeRecord;
import cn.copera.dyy.entity.ExchangeRule;
import cn.copera.dyy.entity.Log;
import cn.copera.dyy.entity.Order;
import cn.copera.dyy.entity.Shop;
import cn.copera.dyy.entity.Track;
import cn.copera.dyy.entity.UserShop;
import cn.copera.dyy.service.ExchangeRecordService;
import cn.copera.dyy.service.ExchangeRuleService;
import cn.copera.dyy.service.LogService;
import cn.copera.dyy.service.OrderService;
import cn.copera.dyy.service.ShopService;
import cn.copera.dyy.service.TrackService;
import cn.copera.dyy.service.UserService;
import cn.copera.dyy.service.UserShopService;

/**
 * 卡点兑换Controller
 * 
 * 
 */
@Controller
@RequestMapping(value = "${adminPath}/exchangeRecord")
public class ExchangeRecordController extends BaseController {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	ExchangeRecordService exchangeRecordService;
	@Autowired
	ShopService shopService;
	@Autowired
	ExchangeRuleService exchangeRuleService;
	@Autowired
	UserService userService;
	@Autowired
	TrackService trackService;
	@Autowired
	private UserShopService userShopService;
	@Autowired
	private LogService logService;
	@Autowired
	OrderService orderService;
	@RequestMapping(value="/upload")
	@ResponseBody
	public  Map<String, Object> upload(HttpServletRequest request, PrintWriter out) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		MultipartFile multipartFile = null;
		
		String path = "/images/";
		String realPath = request.getSession().getServletContext().getRealPath(path);
		FileUtils.createDirectory(realPath);
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
		String filename = sf.format(new Date())+".jpg";
		Map<String, Object> map = new HashMap<String,Object>();
		String jd =  request.getParameter("jd");
		for (Map.Entry<String, MultipartFile> set : fileMap.entrySet()) {
			multipartFile = set.getValue();  // 文件
			
			if(multipartFile != null && multipartFile.getSize() > 0){
				FileOutputStream fs;
				try {
					fs = new FileOutputStream(realPath + "/"+ filename);
			        byte[] buffer =new byte[1024*1024];
			       
			        int byteread = 0;
			        InputStream stream = multipartFile.getInputStream();
			        while ((byteread=stream.read(buffer))!=-1)
			        {
			          
			           fs.write(buffer,0,byteread);
			           fs.flush();
			        } 
			        fs.close();
			        stream.close();
			        File f = new File(realPath + "/"+ filename);
					FileInputStream fis;
					try {
						fis = new FileInputStream(f);
						BufferedImage bufferedImg = ImageIO.read(fis);
						int imgWidth = bufferedImg.getWidth();
						if(imgWidth>720){
							ImageUtil.resize(f, f, 720, 1f);
						}
						float scale=1f;
						long size = f.length()/1024;
						while(size>100){
							scale-=0.1f;
							ImageUtil.resize(f, f, 720, scale);
							size = f.length()/1024;
						}
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(jd!=null&&!jd.equals("")){
						 BufferedImage src = ImageIO.read(f);   
						 BufferedImage des = RotateImage.Rotate(src, Integer.parseInt(jd));
						 String fn =  sf.format(new Date())+".jpg";
						 ImageIO.write(des,"jpg",new File(realPath + "/"+ fn));
						 int width = des.getWidth();   
				         int height = des.getHeight(); 
				         map.put("path", path+fn);
				         map.put("status", "success");
				         map.put("width", width);
				         map.put("height", height);
					}
			          
			       
			       
				} catch (IOException e) {
					 map.put("status", "error");
					e.printStackTrace();
				}
			}
		}
		 return map;
	}
    /**
     * 兑换确认
     * @return
     * @throws ParseException 
     */
	@RequestMapping(value = "/confirm", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> confirm(@RequestParam(required = false) String nickName,String ruleId,String shopId) throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(nickName)){

			UserShop userShop = userShopService.findUserShop(shopId);
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
			if (userShop != null) {
				Log log = logService.find(shopId,ruleId,nickName);
				String message = "";
				boolean bool = true;
				if ("yes".equals(log.getCheckorno())) {
					bool = false;
					message = "该申请已兑换，不能再次兑换";
				}else if ("back".equals(log.getCheckorno())) {
					bool = false;
					message = "该申请已撤销，不能兑换";
				}else {
					Date date1 = format.parse(format.format(new Date()));
					Date date2 = format.parse(format.format(log.getValidDate()));
					long diff = date2.getTime() - date1.getTime();
					if (diff < 0) {
						bool = false;
						message = "该申请已过期，请重新申请兑换";
					}
				}
				
				if (bool) {
					//总的可用卡点
					Long countPoint = trackService.countPoint(shopId, nickName);
					ExchangeRule rule =exchangeRuleService.get(ruleId);
					if(rule != null && countPoint != null && countPoint >= rule.getPointCount()){
						
						Shop shop = shopService.get(shopId);
						
						List<Track> list = trackService.findTrack4Exchange(shopId, nickName);
				        Integer count = rule.getPointCount();
				        
				        //已兑换的卡点
				        List<Track> exchangTrack = new ArrayList<Track>();
				        for (Track tr : list) {
				        	if (count >= tr.getUsableCount()) {
								count = count-tr.getUsableCount();
								tr.setUsableCount(0);
								tr.setState("1");
								exchangTrack.add(tr);
							}else {
								tr.setUsableCount(tr.getUsableCount()-count);
								count = 0;
								exchangTrack.add(tr);
								break;
							}
						}
				        ExchangeRecord record= new ExchangeRecord();
						record.setNickName(nickName);
						record.setExchangePoint(rule.getPointCount()+"");
						record.setExchangeContent(rule.getExchangeContent());
						record.setExchangeDate(new Date());
						record.setShop(shop);
						record.setExchangeDateStr(format.format(new Date()));
						record.setExchangeUser(shop.getLoginName());
						exchangeRecordService.save(record);

						map.put("exchangeToday", exchangeRecordService.countExchangeToday(shopId));
						map.put("message", "success");
						
						//保存已兑换的卡点状态
						trackService.changeTrackState(exchangTrack);
						
						log.setCheckorno("yes");
						logService.save(log);
//						logService.deleteById(log.getId());
						UserShop shop2 = userShopService.findUserShopByOpenid(shopId, nickName);
						shop2.setOperate(new Date());
						userShopService.update(shop2);
						
						Order order = orderService.findOrder(shopId, nickName);
						if(order!=null){
							order.setTime(new Date());
							orderService.save(order);
						}						
					}else{
						map.put("message", "卡点不足");
					}
				}else {
					map.put("message", message);
				}
			}else {
				map.put("message", "系统中不存在有关此二维码的信息");
			}
		}
		else{
			map.put("message", "系统中不存在有关此二维码的信息");
		}
		return map;
	}

	//今天的兑换
	@RequestMapping(value="/findExchangeToday",method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> findExchangeToday(@RequestParam(required = false) String shopId){
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("exchangeList", exchangeRecordService.findExchangeToday(shopId));
		return map;
	}		
	//最近3天的兑换
	@RequestMapping(value="/findExchangeOld",method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> findExchangeOld(@RequestParam(required = false) String shopId){
		return exchangeRecordService.findExchangeOld(shopId);
	}		

	@RequestMapping(value="/ruleList",method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> ruleList(@RequestParam(required = false) String shopId){
		Map<String, Object> map = new HashMap<String,Object>();
		List<ExchangeRule> list =exchangeRuleService.findById(shopId);
				map.put("size", list.size());
		return map;
	}
	
	@RequestMapping(value="/deleteRule",method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> deleteUser(@RequestParam(required = false) String ruleId,String shopId){
		exchangeRuleService.deleteById(ruleId);
		Map<String, Object> map = new HashMap<String,Object>();
		List<ExchangeRule> list =exchangeRuleService.findById(shopId);
				map.put("list", list);
				map.put("message", "删除成功");
		return map;
	}

	@RequestMapping(value="/ruleList1",method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> listRule1(@RequestParam(required = false) String id){
		Map<String, Object> map = new HashMap<String,Object>();
		List<ExchangeRule> list =exchangeRuleService.findById(id);
				map.put("list", list);
		return map;
	}	
	@RequestMapping(value="/saveRule",method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> saveUser(@RequestParam(required = false) String id,String userName,String userPass,String path,String width,String height,String jd){
		
		userPass = changeToWord(userPass);
		Map<String, Object> map = new HashMap<String,Object>();
		List<ExchangeRule> list =exchangeRuleService.findById(id);
		Shop shop1 = shopService.get(id);
		try {
			if(list.size()<3){
				ExchangeRule rule = new ExchangeRule();
				rule.setShop(shop1);
				rule.setPointCount(Integer.parseInt(userName));
				rule.setCreateDate(new Date());
				rule.setExchangeContent(userPass);
				rule.setImagePath(path);
				rule.setWidth(Integer.parseInt(width==null||width.equals("")?"0":width));
				rule.setHeigth(Integer.parseInt(height==null||height.equals("")?"0":height));
				rule.setJd(Integer.parseInt(jd==null||jd.equals("")?"0":jd));
				exchangeRuleService.save(rule);	
				List<Order> olist = orderService.findById(id);
				if(olist.isEmpty()){
				}else{
					for(Order o : olist){
						o.setTime(new Date());
						orderService.save(o);
					}
				}
				list.add(rule);
				map.put("list", list);
				map.put("message", "保存成功");
			}else{
				map.put("message", "最多只能添加三条规则");
			}
		} catch (Exception e) {
			map.put("message", "保存失败，请输入合法字符");
		}
		return map;
	}	

	//根据id查找规则
	@RequestMapping(value="/findRuleById",method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> findRuleById(@RequestParam(required = false) String ruleId){
		Map<String, Object> map = new HashMap<String,Object>();
		ExchangeRule rule = exchangeRuleService.get(ruleId);
		map.put("pointCount",rule.getPointCount());
		map.put("exchangeContent",rule.getExchangeContent());
		return map;
	}	
	
	/**
	 * 将获取的Unicode字符串解码成中文字
	 */
	public static String changeToWord(String str) {
		String retData = null;
		String tempStr = new String(str);
		String[] chStr = new String[str.length()/4];
		for(int i=0;i<str.length();i++){
			if(i%4==3){
				chStr[i/4] = new String(tempStr.substring(0, 4));
				tempStr = tempStr.substring(4, tempStr.length());
			}
		}
		char[] retChar = new char[chStr.length];
		for(int i=0;i<chStr.length;i++){
			retChar[i] = (char) Integer.parseInt(chStr[i], 16);
		}
		retData = String.valueOf(retChar, 0, retChar.length);
		return retData;
	}
}
